<template>
	<a-spin :spinning="spinning" tip="正在下课..." style="height: 100%" :delay="500">
		<div class="answerCenter">
			<a-modal v-model="showSdk" title="提示">
				<p>
					也许SDK断开了，请尝试
					<span style="color: #f00">重启SDK</span>
					。
				</p>
				<p>
					如果你您的SDK是启动的，请尝试
					<span style="color: #f00">重连设备</span>
				</p>
				<template slot="footer">
					<a-button key="back" @click="connctWebscoket">重连设备</a-button>
					<a-button key="submit" type="primary" @click="connctSDK">重启SDK</a-button>
				</template>
			</a-modal>
			<template v-if="currentKey">
				<component
					:is="filterMainComponent(currentKey)"
					:formData="formData"
					:ref="'component' + currentKey"
					:machineData="machineData"
					:studentList="studentList"
					@stopBind="stopBindStudent"
					@startBind="bindStudent"
					@checkMenu="checkMenu"
				></component>
			</template>
			<template>
				<!-- 菜单栏 -->
				<div
					id="toolBottombar"
					class="toolBottombar"
					v-if="!['mole', 'redpack'].includes(currentKey) && !isStartBind && !(isAnswering - 0)"
				>
					<div class="toolbar flex" ref="toolBar">
						<div
							class="tool-item"
							v-for="(item, index) in showMenuList"
							:key="index"
							:class="{ 'tab-line': item.group == 1 }"
						>
							<a
								href="javascript:;"
								@click.stop="changeTab(item.value)"
								:class="[formData.topicType === item.value ? 'active' : '']"
								>{{ item.text }}</a
							>
						</div>
						<div class="tool-item tab-line" v-if="morelist.length > 0">
							<a-popover placement="top" trigger="click" v-model="showMore">
								<template slot="content">
									<div class="popoverbox flex flex-wrap">
										<a
											class="flex flex-v"
											@click="changeTab(item.value)"
											href="javascript:;"
											v-for="(item, index) in morelist"
											><img
												:src="
													formData.topicType === item.value
														? item.img + '_selected.png'
														: item.img + '.png'
												"
												class="icon"
											/>
											<div>{{ item.text }}</div>
										</a>
									</div>
								</template>
								<a
									class="flex flex-v"
									href="javascript:;"
									:class="[
										morelist.some((item) => formData.topicType === item.value) ? 'active' : '',
									]"
								>
									<div>更多</div>
								</a>
							</a-popover>
						</div>
					</div>
				</div>
			</template>
		</div>
	</a-spin>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
import { testTypeListEnum } from '@/utils/enumeration.js';
import { debounce } from '@/utils/base.js';
function drag(el) {
	const translate = { x: 0, y: 0 }, // 初始状态translate值
		createMover = (tapFrom) => {
			const origin = { ...translate };
			return (tapTo) => {
				translate.x = tapTo.clientX - tapFrom.clientX + origin.x;
				translate.y = tapTo.clientY - tapFrom.clientY + origin.y;
				el.style.setProperty('transform', buildTransform());
			};
		},
		{ transform } = window.getComputedStyle(el);

	let buildTransform;
	// getComputedStyle读取的transform只有矩阵和none两种情况
	if (transform.startsWith('matrix')) {
		const matrix = transform.slice(7, -1).split(', '),
			[x, y] = matrix.splice(4); // 矩阵最后两个是translate值
		// 修改初始值
		translate.x = parseInt(x);
		translate.y = parseInt(y);
		buildTransform = () => `matrix(${matrix.join(',')},${translate.x},${translate.y})`;
	} else buildTransform = () => `translate(${translate.x}px,${translate.y}px)`;

	// 触屏
	el.addEventListener('touchstart', (e) => {
		e.stopPropagation();
		const moveTo = createMover(e.touches[0]),
			onMove = (e) => {
				moveTo(e.touches[0]);
			},
			prevent = (eve) => {
				eve.preventDefault();
			},
			onEnd = () => {
				window.removeEventListener('touchmove', prevent);
				el.removeEventListener('touchmove', onMove);
				el.removeEventListener('touchend', onEnd);
				//缓存一下现在的位置
				sessionStorage.setItem('toolbarTransform', buildTransform());
			};
		window.addEventListener('touchmove', prevent, { passive: false });
		el.addEventListener('touchmove', onMove);
		el.addEventListener('touchend', onEnd);
	});

	// 鼠标
	el.addEventListener('mousedown', (e) => {
		e.stopPropagation();
		// 判断 target 是否是你关心的子元素
		if (e.target.classList.contains('toolBottombar')) {
			// 这里读的是内联样式的值，如果没有值待松开后删除即可
			const cursor = el.style.getPropertyValue('cursor'),
				userSelect = el.style.getPropertyValue('user-select'),
				onMove = createMover(e),
				onEnd = () => {
					document.removeEventListener('mousemove', onMove);
					el.removeEventListener('mouseup', onEnd);
					if (!cursor) el.style.removeProperty('cursor');
					else el.style.setProperty('cursor', cursor);
					if (!userSelect) el.style.removeProperty('user-select');
					else el.style.setProperty('user-select', userSelect);
					//缓存一下现在的位置
					sessionStorage.setItem('toolbarTransform', buildTransform());
				};
			document.addEventListener('mousemove', onMove);
			el.addEventListener('mouseup', onEnd);
			el.style.setProperty('cursor', 'move');
			el.style.setProperty('user-select', 'none');
		}
	});
}

//题目类型
const topicTypeListEnum = [
	{
		value: 0,
		text: '单选题',
		type: 's',
		wareVersion: '',
	},
	{
		value: 1,
		text: '多选题',
		type: 'm',
		wareVersion: '',
	},
	{
		value: 2,
		text: '判断题',
		type: 'j',
		wareVersion: '',
	},
	{
		value: 5,
		text: '数字题',
		type: 'f',
		wareVersion: '',
	},

	{
		group: '1',
		value: 9,
		text: '语音答题',
		wareVersion: '554',
		currentKey: 'microphone',
	},
	{
		value: 8,
		text: 'AI问答',
		wareVersion: '554',
		currentKey: 'speechAnswer',
	},
	{
		value: 10,
		text: '语音测评',
		wareVersion: '554',
		currentKey: 'evaluation',
	},
	{
		group: '1',
		value: 11,
		text: '答题统计',
		img: '/impromptu/toolbar/icon02',
		currentKey: 'tempAnswerCount',
	},
	{
		value: 12,
		text: '表扬',
		img: '/impromptu/toolbar/icon14',
		currentKey: 'praise',
	},
	{
		group: '1',
		value: 13,
		text: '学生名单',
		perms: 'doExercise:studentlist',
		img: '/impromptu/toolbar/icon01',
		currentKey: 'studentlist',
	},
	{
		value: 14,
		text: '学生分组',
		perms: 'doExercise:group',
		img: '/impromptu/toolbar/icon15',
		currentKey: 'group',
	},
	{
		group: '1',
		value: 15,
		text: '抢红包',
		perms: 'doExercise:redpack',
		img: '/impromptu/toolbar/icon16',
		currentKey: 'redpack',
	},
	{
		value: 16,
		text: '打地鼠',
		perms: 'doExercise:mole',
		img: '/impromptu/toolbar/icon17',
		currentKey: 'mole',
	},
	{
		value: 17,
		text: 'web页面',
		img: '/impromptu/toolbar/icon18',
	},
];
import { mainMoudelComponent } from './components/index.js';
import { ch2Unicdoe, padZero } from '@/utils/base';
import { menuList } from '@/utils/enumeration.js';
//监听小程序混合方法
import minProjectMixins from '@/mixins/minProjectMixins.js';
var startTime = '';
export default {
	name: 'doExercise',
	mixins: [minProjectMixins],
	data() {
		return {
			currentKey: 'startAnswer',
			oldcurrentKey: 'startAnswer',
			mainMoudelComponent,
			formData: {
				topicType: 0,
				testQuestId: '',
				tabType: '',
				classId: '',
				className: '',
			},
			topicTypeListEnum: topicTypeListEnum,
			menuList: menuList, //左侧工具栏
			curMenu: '', //左侧工具默认值
			toolBarWidth: null,
			allstudentList: [], //学生数组
			isStartClassComp: false, //默认不是开始上课页面
			machineData: {
				machId: '',
				online: 0,
				wareVersion: '', //接收器硬件版本号
				version: '', //接收器软件版本
				sdk_ver: '', //sdk 版本
			},
			isStartBind: false,
			showSdk: false,
			spinning: false,
			csId: '',
			signInId: '', //签到的id
			handUserList: [], //举手的学生
			hasMove: false,
			morelist: [],
			showMore: false,
		};
	},
	created() {
		this.getTeacherInfo(); //获取老师信息
		let _this = this;
		//监听下课
		if (window.ipcRenderer) {
			window.ipcRenderer.once('exitdirebro', (e, data) => {
				if (!_this.spinning) {
					_this.endClass();
				}
			});
		}
	},
	mounted() {},
	computed: {
		...mapState({
			user: (state) => state.user,
			deviceType: (state) => state.websockStore.deviceType,
			studentList: (state) => state.websockStore.studentList,
			isAnswering: (state) => state.websockStore.isAnswering,
			eventlist: (state) => state.websockStore.eventlist,
			websocketConncted: (state) => state.websockStore.conncted,
			rabbitmqConncted: (state) => state.rabbitMQStore.conncted,
			minProjectConncted: (state) => state.minProjectStore.conncted,
			stopDeviceEventList: (state) => state.websockStore.stopDeviceEventList,
			whiteList: (state) => state.websockStore.whiteList,
			hostname: (state) => state.hostname,
			isPro: (state) => state.isPro,
			orgIsWired: (state) => state.user.orgIsWired,
			teacherInfo: (state) => state.user.teacherInfo,
		}),
		//设备在线状态
		pushOnlineEvent() {
			return this.$store.getters.onEvent('online');
		},
		//更新学生名单
		pushUpdateStudentEvent() {
			return this.$store.getters.onEvent('updateStudent');
		},
		//552D 绑定成功
		updateWirelessCard() {
			return this.$store.getters.onEvent('update_wireless_card');
		},
		//姓名配置成功
		nameConfigUpdate() {
			return this.$store.getters.onEvent('name_update');
		},
		//同步552G 答题器在线状态成功   get_dtq_status 和sync_ans_uidlist 这两个指令成功后，都会触发这个指令
		updateDtqStatus() {
			return this.$store.getters.onEvent('update_dtq_status');
		},
		// 刷卡上报
		card_update() {
			return this.$store.getters.onEvent('card_update');
		},
		// 获取设备成功后回调
		getDeviceInfo() {
			return this.$store.getters.onEvent('getDeviceInfo');
		},
		toast() {
			return this.$store.getters.onEvent('toast');
		},
		//sdk 断开，需要重启软件
		sdkoffline() {
			return this.$store.getters.onEvent('sdkoffline');
		},
		//是否可以发送绑卡指令
		isCanBindStu() {
			return {
				allstudentList: this.allstudentList,
				online: this.machineData.online,
				machId: this.machineData.machId,
				isStartClassComp: this.isStartClassComp,
				deviceType: this.deviceType,
			};
		},
		//是否有套题
		isHasAnswerTest() {
			return this.$_has('quiz') || this.$_has('homework');
		},
		//是否有学生名单,临时题统计
		isHasleftMenuList() {
			let comList = ['doExercise:studentlist', 'impromptuQA:answerCount']; //左侧菜单权限
			let isHasComList = [];
			comList.forEach((item) => {
				if (this.$_has(item)) {
					isHasComList.push(item);
				}
			});
			return isHasComList;
		},
		//同步设备信息到小程序
		syncBaseData() {
			return {
				machineData: this.machineData,
				minProjectLogin: this.minProjectLogin,
				stopDeviceEventList: this.stopDeviceEventList,
				studentList: this.studentList,
			};
		},
		//签到
		updateSignIn() {
			return this.$store.getters.onEvent('sign_in_update');
		},
		//举手
		updateRaiseHand() {
			return this.$store.getters.onEvent('raise_hand_update');
		},
		//是否是语音设备
		isVoiceDevice() {
			return ['RP554', 'RP555P'].includes(this.machineData.wareVersion);
		},
		showMenuList() {
			let list = this.topicTypeListEnum;
			if (this.isVoiceDevice) {
				//没有数字题
				list = list.filter((item) => item.value != 5);
			} else {
				list = list.filter((item) => item.value != 8 && item.value != 9 && item.value != 10);
			}
			if (!this.isHasAnswerTest) {
				list = list.filter((item) => item.value != 99);
			}
			//如果科目不是英语，则不显示语音测评
			if (this.formData.subjectCode != 2) {
				list = list.filter((item) => item.value != 10);
			}
			if (list && list.length > 6) {
				this.morelist = list.slice(6, list.length);
			} else {
				this.morelist = [];
			}
			setTimeout(() => {
				this.$forceUpdate();
			}, 500);
			return list.slice(0, 6);
		},
		//是否显示操作栏
		isShowToolbar() {
			return !['mole', 'redpack'].includes(this.currentKey) && !(this.isAnswering - 0);
		},
	},
	watch: {
		$route: {
			handler(to, from) {
				//不是从统计页面回来，才走初始化流程
				if (to.path == '/home') {
					console.log(this.wsUrl);

					console.log('deviceType:>>' + this.deviceType);
					this.currentKey = '';
					this.$nextTick(() => {
						console.log('来自于' + this.currentKey);
						let beginClass = this.$ls.get('beginClass');
						this.csId = beginClass.csId;
						this.classTimeLen = (beginClass.durLesson || 45) * 60 * 1000;
						console.log(beginClass);
						// this.isStartClassComp = !beginClass || (beginClass && Object.keys(beginClass).length == 0);
						// console.log(this.isStartClassComp);
						localStorage.removeItem('hasTipsStuState'); //发题时是否已经提示过学生绑定状态
						this.spinning = false;
						this.getInit();
					});
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//监听是否有菜单操作栏
		isShowToolbar: {
			handler(newValue, oldValue) {
				if (newValue && oldValue != newValue) {
					let toolbarTransform = sessionStorage.getItem('toolbarTransform');
					this.$nextTick(() => {
						if (toolbarTransform) {
							document.getElementById('toolBottombar').style.setProperty('transform', toolbarTransform);
						}
						drag(document.getElementById('toolBottombar'));
					});
				}
			},
			immediate: true,
		},

		//监听是否上课
		isStartClassComp(newValue, oldValue) {
			if (newValue != oldValue) {
				this.getInit();
			}
		},
		//监听接收器在线状态
		pushOnlineEvent: {
			handler(newValue, oldValue) {
				if (newValue && newValue != oldValue) {
					console.log('设备在离线状态' + JSON.stringify(newValue));
					if (this.pushOnlineEvent && JSON.stringify(this.pushOnlineEvent) != '{}') {
						if (this.pushOnlineEvent.machineId == this.machineData.machId) {
							if (this.pushOnlineEvent.val == 0) {
								this.machineData.online = this.pushOnlineEvent.val;
								this.$message.error('设备' + this.machineData.machId + '离线！');
								/* 将所有答题器状态改成离线 */
								if (this.studentList && this.studentList.length > 0) {
									let studentList = [...this.studentList];
									studentList.forEach((item) => {
										item.status = '0';
									});
									this.SET_studentList(studentList);
								}
								this.SET_WHITELIST([]);
							} else {
								this.$message.success('设备' + this.machineData.machId + '上线！');
							}
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},

		//学生绑定成功
		updateWirelessCard: {
			handler(newValue, oldValue) {
				if (newValue && newValue.uID && newValue != oldValue) {
					//先判断学生名单中，有没有这个设备，
					this.getStuNameAndupload(newValue.uID);
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//552G 自动绑卡返回
		updateDtqStatus: {
			handler(newValue, oldValue) {
				if (newValue && newValue.status_list && newValue.status_list.length > 0 && newValue != oldValue) {
					//先判断学生名单中，有没有这个设备，
					let ids = [];
					newValue.status_list.forEach((item) => {
						if (item.online == 1) {
							this.getStuNameAndupload(item.uID);
							ids.push(item.uID);
						}
					});
					this.SET_WHITELIST(ids);
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//刷卡上报
		card_update: {
			handler(newValue, oldValue) {
				if (newValue && newValue.uID && newValue != oldValue) {
					//处于绑卡状态下，判断该设备是否已经绑定
					console.log('isStartBind', this.isStartBind);
					// if (this.isStartBind) {
					if (
						this.isVoiceDevice &&
						this.teacherInfo &&
						this.teacherInfo.machineId &&
						this.teacherInfo.machineId - 0 == newValue.uID - 0
					) {
						let teacherInfo = { ...this.teacherInfo };
						teacherInfo.status = 1;
						this.SET_TEACHER_INFO(teacherInfo);
						this.updateName(newValue.uID, this.teacherInfo.teacherName);
					} else {
						let stuIndex = this.studentList.findIndex((item) => item.machineId - 0 == newValue.uID - 0);
						if (stuIndex > -1) {
							//this.$message.error('答题器' + newValue.uID + '已经绑定过了！');
							//如果这个学生没有在线，则触发绑定
							if (this.studentList[stuIndex].status == 0) {
								if (this.isVoiceDevice) {
									// 语音设备，刷卡绑定
									this.getStuNameAndupload(newValue.uID);
								} else {
									this.bindStudent([newValue.uID]);
								}
							}
						} else {
							//需要回填没有答题器学生或者替换选中的答题器
							//优先查找选中的名单
							stuIndex = this.studentList.findIndex((item) => !item.machineId && item.checked);
							if (stuIndex == -1) {
								//按顺序查找选中学生替换
								stuIndex = this.studentList.findIndex((item) => item.checked);
							}
							if (stuIndex == -1) {
								//按顺序查找最近一个没有设备的学生绑定
								stuIndex = this.studentList.findIndex((item) => !item.machineId);
							}

							if (stuIndex > -1) {
								//有未绑定的学生，才需要绑定
								let stu = this.studentList[stuIndex];
								let newstudentList = [...this.studentList];
								let uID = padZero(newValue.uID);
								newstudentList[stuIndex].machineId = uID;
								newstudentList[stuIndex].checked = false;
								this.SET_studentList(newstudentList);
								if (this.isVoiceDevice) {
									// 46设备，刷卡绑定
									this.getStuNameAndupload(newValue.uID);
								} else {
									this.bindStudent([newValue.uID]);
								}
							}
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//获取设备信息
		getDeviceInfo: {
			handler(newValue, oldValue) {
				if (newValue && JSON.stringify(newValue) != JSON.stringify(oldValue)) {
					//如果是正在上课，处理，因为清空白名单后，也会回调这个参数
					if (!this.isStartClassComp && !this.spinning) {
						//查询白名单数据，如果在线，不在发送绑卡指令
						console.log('newValue.ports.list', newValue.ports[0].list);
						let ids = [];
						if (newValue.ports[0].list && newValue.ports[0].list.length > 0) {
							if (newValue.dev != 'RP552G') {
								ids = newValue.ports[0].list.map((item) => item.uID);
								if (this.studentList && this.studentList.length > 0) {
									let studentList = [...this.studentList];
									studentList.forEach((item) => {
										if (ids.includes(item.machineId - 0)) {
											item.status = '1';
										} else {
											item.status = '0';
										}
									});
									this.SET_studentList(studentList);
								}
							} else if (newValue.dev == 'RP552G') {
								//同步在线的答题器
								this.WEBSOCKET_SEND({ fun: 'get_dtq_status' });
							}
						}
						this.SET_WHITELIST(ids);
						this.machineData = {
							machId: newValue.dev_sn,
							online: 1,
							wareVersion: newValue.dev,
							version: newValue.version.replace('v', ''),
							sdk_ver: newValue.sdk_ver.replace('v', ''),
						};
						console.log('设备信息' + JSON.stringify(this.machineData));
						let beginClassData = this.$ls.get('beginClass'); //上课数据
						this.setWlList({
							classId: beginClassData.classId,
							machId: newValue.dev_sn,
							sdkVer: newValue.sdk_ver,
							softVersion: newValue.version,
							wareVersion: newValue.dev,
							machType: 0,
						});
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},

		toast: {
			handler(newValue, oldValue) {
				if (newValue && newValue != oldValue) {
					if (newValue.msgtype == 'success') {
						this.$message.success(newValue.msg);
					} else {
						this.$message.error(newValue.msg);
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		isCanBindStu: {
			handler(newValue, oldValue) {
				//开始上课后，才能开始绑卡
				if (
					!this.isStartClassComp &&
					newValue &&
					newValue.allstudentList &&
					newValue.online &&
					newValue.machId &&
					newValue.deviceType == 'wired' &&
					JSON.stringify(newValue) != JSON.stringify(oldValue)
				) {
					this.bindStudent();
					if (this.$_has('doExercise:hand') && !this.isVoiceDevice) {
						//开始举手指令
						this.WEBSOCKET_SEND({ fun: 'raise_hand_start' });
						//下课的时候统一处理停止指令
						if (!this.stopDeviceEventList.includes('raise_hand_stop')) {
							let eventlist = this.stopDeviceEventList || [];
							eventlist.push('raise_hand_stop');
							this.SET_STOPDEVICEEVENTLIST(eventlist);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//websocket 断开后操作
		sdkoffline: {
			handler(newValue, oldValue) {
				//开始上课后，才能开始绑卡
				console.log('sdkoffline', newValue);
				if (newValue && !this.isStartClassComp && this.$route.path == '/home') {
					if (newValue.code == 1006 && !this.spinning) {
						this.machineData.online = 0;
						this.showSdk = true;
					} else {
						this.spinning = false;
						//清空学生名单
						this.SET_studentList([]);
						this.allstudentList = [];
						//清空设备信息
						this.machineData = {
							machId: '',
							online: 0,
							wareVersion: '',
							sdk_ver: '',
							version: '',
						};
						this.CLEAR_EVENTLIST();
						//清空未处理的推送记录。
						this.$router.replace({
							path: '/user/login',
						});
						console.log('startTime', new Date().getTime() - startTime);
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//552D 552G姓名更新后的回调
		nameConfigUpdate: {
			handler(newValue, oldValue) {
				if (newValue && newValue.uID && newValue != oldValue) {
					//学生名单如果绑定过了名称，则设置状态
					let newstuList = [...this.studentList];
					newstuList.forEach((item) => {
						if (newValue.uID - 0 == item.machineId - 0) {
							item.status = '1'; //偶尔出现，同步的指令没有改变学生绑定状态的情况，再这里再次同步一次学生绑定状态
							item.hasName = '1';
						}
					});
					this.SET_studentList(newstuList);
					if (this.machineData.wareVersion != 'RP552G' && !this.isVoiceDevice) {
						//所有的学生姓名配置成功。需要关闭姓名回显指令
						if (
							newstuList.every((item) => item.hasName == '1') &&
							this.stopDeviceEventList.includes('name_stop')
						) {
							this.WEBSOCKET_SEND({ fun: 'name_stop' });
							let eventlist = this.stopDeviceEventList;
							eventlist = eventlist.filter((item) => item != 'name_stop');
							this.SET_STOPDEVICEEVENTLIST(eventlist);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		updateSignIn: {
			handler(newValue, oldValue) {
				if (newValue && newValue.uID && newValue != oldValue) {
					if (!this.signInId) {
						let signInInfo = this.$ls.get('signInInfo') || {};
						if (signInInfo.signInId && signInInfo.csId == this.csId) {
							this.signInId = signInInfo.signInId;
						} else {
							return;
						}
					}

					if (this.studentList && this.studentList.length > 0) {
						let info = this.studentList.find((item) => item.machineId - 0 == newValue.uID);
						if (info) {
							let msg = {
								signInid: this.signInId,
								csId: this.csId,
								time: newValue.time,
								studId: info.studId,
							};
							this.signInUpdate(msg);
							/* 更新到签到页面 */
							this.$refs.componentsignin && this.$refs.componentsignin.updateList(msg);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		//举手
		updateRaiseHand: {
			handler(newValue, oldValue) {
				if (newValue && newValue.uID && newValue != oldValue) {
					if (
						this.studentList &&
						this.studentList.length > 0 &&
						this.studentList.some((item) => item.machineId - 0 == newValue.uID) &&
						(this.handUserList.length == 0 ||
							this.handUserList.some((item) => item.machineId - 0 != newValue.uID))
					) {
						this.handUserList.push(newValue.uID);
						/* 更新到举手页面 */
						if (this.$refs.componenthand) {
							let list = [];
							this.handUserList.forEach((item) => {
								let info = this.studentList.find((stud) => stud.machineId - 0 == item);
								if (info) {
									list.push(info);
								}
							});
							this.$refs.componenthand.updateList(list);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},
	methods: {
		...mapMutations([
			'WEBSOCKET_INIT',
			'WEBSOCKET_SEND',
			'SET_studentList',
			'WEBSOCKET_CLOSE',
			'WEBSOCKET_RECONNECT',
			'SET_isAnswering',
			'CLEAR_EVENTLIST',
			'RABBITMQ_INIT',
			'destroyConnection',
			'SET_STOPDEVICEEVENTLIST',
			'SET_WHITELIST',
			'MINPROJECT_INIT',
			'MINPROJECT_CLOSE',
			'SET_tempTestData',
			'REMOVE_tempTestData',
			'sign_RABBITMQ_SEND',
			'SET_ANS_ID',
			'SET_TEACHER_INFO',
		]),
		async getInit() {
			this.getDefaultCompnent();
			if (!this.isStartClassComp) {
				let qyParams = this.$ls.get('beginClass'); //上课数据
				let startClassInfo = this.$ls.get('startClassInfo');
				this.WEBSOCKET_INIT('ws://127.0.0.1:8011', this.deviceType);
				let APP_MINPROJECT_API = process.env.VUE_APP_MINPROJECT_API;
				this.MINPROJECT_INIT(APP_MINPROJECT_API + this.csId);

				//连接rabbitMQ
				this.RABBITMQ_INIT();
				if (qyParams && JSON.stringify(qyParams) != '{}') {
					for (var key in qyParams) {
						if (key != 'isBegin') {
							this.formData[key] = qyParams[key];
						}
					}
				}
				this.allstudentList = [];
				let proList = [this.getStuList(this.formData.classId)];
				Promise.all(proList);
			}
		},

		//渲染模块组件
		filterMainComponent(id) {
			/**
			 * 极少概率出现没有id的情况，当没有时，判断权限有无即兴问题，无则走quiz组件（随堂检测和课后作业均用的quiz组件）
			 */
			id = id || 'startAnswer';
			for (var key in mainMoudelComponent) {
				if (id == key) {
					return mainMoudelComponent[key];
				}
			}
		},
		//获取当前页面组件
		getDefaultCompnent(platform, params) {
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			let testData = this.$ls.get('testData'); //上课数据
			if (beginClassData && JSON.stringify(beginClassData) != '{}') {
				let { topicType } = {
					...beginClassData,
				};
				if (topicType >= 8 && topicType <= 16) {
					let info = this.topicTypeListEnum.find((item) => item.value == topicType);
					this.currentKey = info.currentKey;
				} else if (topicType != 99) {
					this.currentKey = 'startAnswer';
					if (this.$refs.componentstartAnswer) {
						this.$refs.componentstartAnswer.initData();
					}
				}
				this.oldcurrentKey = this.currentKey;
			}
		},
		//切换题目类型
		async changeTab(value, platform, params) {
			this.showMore = false;
			console.log('doExercise切换题目类型' + JSON.stringify(value));
			let testData = this.$ls.get('testData');
			let testComponet = this.$ls.get('testComponet');
			console.log('答题测试组件' + JSON.stringify(testComponet));
			if (value != 17) {
				localStorage.setItem('tempsdTestQuestId', '');
				localStorage.setItem('sdTestQuestId', '');
				this.SET_isAnswering(0);
				this.formData.topicType = value;
				let beginClassData = this.$ls.get('beginClass'); //上课数据
				beginClassData.topicType = value;
				this.$ls.set('beginClass', beginClassData);
			}
			if (value >= 8 && value <= 16) {
				let info = this.topicTypeListEnum.find((item) => item.value == value);
				this.currentKey = info.currentKey;
			} else if (value == 17) {
				/* 跳转到web */
				if (window.shell) {
					let token = sessionStorage.getItem('access_token');
					//
					let winUrl =
						process.env.NODE_ENV === 'development' ? `http://localhost:8000/` : `https://zdx.ai-boats.com/`;
					window.shell.openExternal(winUrl + '#win?token=' + token);
				}
			} else {
				this.currentKey = 'startAnswer';
				/* 如果是临时题组件页面 */
				if (this.$refs.componentstartAnswer) {
					await this.$refs.componentstartAnswer.changeTab(this.formData.topicType);
					await this.$refs.componentstartAnswer.getDefaultFormData();
				}
			}

			this.oldcurrentKey = this.currentKey;
		},

		//关闭组件后，返回的页面
		checkMenu(item, isSaveOldcurrentKey) {
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			let testData = this.$ls.get('testData');
			//套题操作页面组件key
			let testComponet = this.$ls.get('testComponet');

			/* 判断是否抢答 */
			let isQuickanswer = this.$ls.get('isQuickanswer') || '';
			if (!!isQuickanswer) {
				this.$message.error('请先停止抢答！');
				return;
			}
			/* 判断是否教学反馈 */
			let feedbackId = this.$ls.get('feedbackId') || '';
			if (!!feedbackId) {
				this.$message.error('请先停止教学反馈！');
				return;
			}
			/* 判断语音题 */
			let questId = this.$ls.get('questId');
			if (!!feedbackId) {
				this.$message.error('请先停止语音题！');
				return;
			}
			/* 判断是否举手 。关闭举手弹出框清空之前的举手信息*/
			if (item.type == 'hand' && item.type == this.currentKey) {
				this.handUserList = [];
			}
			/* 判断是否再抢红包 */
			let redpackId = this.$ls.get('redpackId') || '';
			if (!!redpackId) {
				this.$message.error('请先停止抢红包！');
				return;
			}
			/* 判断是否在打地鼠 */
			let moleId = this.$ls.get('moleId') || '';
			if (!!moleId) {
				this.$message.error('请先停止打地鼠！');
				return;
			}
			/* 签到，举手是554没有的功能 */
			if (this.isVoiceDevice && (item.type == 'hand' || item.type == 'signin')) {
				this.$message.error('语音接收器不支持这个功能！');
				return;
			}
			/* 如果现在isAnswering ，则不能跳转到，抢红包,打地鼠，抢答，教学反馈 ，抽答 */
			if (
				this.isAnswering - 0 &&
				['redpack', 'mole', 'quickanswer', 'interaction', 'drawstraws'].includes(item.type)
			) {
				this.$message.error('请先停止答题！');
				return;
			}
			if (item.type == this.currentKey) {
				this.currentKey =
					!this.oldcurrentKey || this.oldcurrentKey == this.currentKey ? 'startAnswer' : this.oldcurrentKey;
				if (this.currentKey == 'startAnswer') {
					this.formData.topicType = 0;
					let beginClassData = this.$ls.get('beginClass'); //上课数据
					beginClassData.topicType = 0;
					this.$ls.set('beginClass', beginClassData);
				}
			} else {
				//this.curMenu = item.type;
				if (isSaveOldcurrentKey) {
				}
				this.currentKey = item.type;
				this.oldcurrentKey = this.currentKey;
			}

			//如果是临时题统计组件页面
			if (this.currentKey == 'studentlist') {
				if (this.deviceType == 'wired') {
					//获取一次答题器状态。防止答题器在白名单中，但是没有回调答题器状态
					this.WEBSOCKET_SEND({
						fun: 'get_dtq_status',
					});
				} else {
					//无线设备，打开学生名单，更新一次学生状态
					this.getStuList(this.formData.classId);
				}
			}
			if (this.currentKey == 'tempAnswerCount') {
				this.formData.topicType = 11;
			}
			/* 如果是临时题组件页面 */
			this.$nextTick(() => {
				if (this.currentKey == 'startAnswer' && this.$refs.componentstartAnswer) {
					this.$refs.componentstartAnswer.changeTab(this.formData.topicType);
					this.$refs.componentstartAnswer.getDefaultFormData();
				}
			});
		},

		//获取学生名单
		getStuList(classId, oldStuList) {
			if (classId) {
				return this.$postAction(this.$sysManageapi.answerUrl.getStuList, {
					classId: classId,
				}).then((res) => {
					if (res && res.code == 1) {
						let studentList = res.data.slice(0, 300).map((item) => {
							item.checked = false;
							item.hasName = item.status;
							if (this.deviceType == 'wired') {
								item.status = '0';
							}
							if (this.whiteList && this.whiteList.length > 0) {
								if (this.whiteList.includes(item.machineId - 0)) {
									item.status = '1';
								}
							}
							return item;
						});
						/*oldStuList:用于无线，点亮答题器会调用接口导致刷卡选中学生状态清空*/
						if (oldStuList && oldStuList.length > 0) {
							let hasCheckedStuList = oldStuList.filter((item) => item.checked);
							for (var i = 0; i < studentList.length; i++) {
								for (var j = 0; j < hasCheckedStuList.length; j++) {
									if (studentList[i].studId == hasCheckedStuList[j].studId) {
										studentList[i].checked = hasCheckedStuList[j].checked;
									}
								}
							}
						}
						this.SET_studentList(studentList);
						this.allstudentList = res.data.map((item) => item.studId);
					}
				});
			}
		},
		//答题器绑定成功后，并回显学生名单
		getStuNameAndupload(uID) {
			let index = this.studentList.findIndex((item) => item.machineId - 0 == uID - 0);
			if (index > -1) {
				if (this.studentList[index].status != 1) {
					//没有绑定才需要重新绑定
					let newstudentList = [...this.studentList];
					if (newstudentList[index].status != 1) {
						let item = newstudentList[index];
						newstudentList[index].status = 1;
						this.SET_studentList(newstudentList);
						this.updateName(uID, item.studName, item.className);
						//如果所有学生都绑定 则结束绑卡
						if (
							newstudentList.every((item) => item.status == 1) &&
							this.machineData.wareVersion != 'RP552G' &&
							!this.isVoiceDevice &&
							this.stopDeviceEventList.includes('wireless_bind_stop')
						) {
							setTimeout(() => {
								this.WEBSOCKET_SEND({ fun: 'wireless_bind_stop' });
								let eventlist = this.stopDeviceEventList;
								if (eventlist && eventlist.length > 0) {
									eventlist = eventlist.filter((item) => item != 'wireless_bind_stop');
									this.SET_STOPDEVICEEVENTLIST(eventlist);
								}
							}, 50);
						}
					}
				}
			}
		},
		//绑定学生
		bindStudent(stuList) {
			//需要使用同步学生名单
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			let list = [];
			if (!stuList) {
				list = this.studentList.filter((item) => item.machineId && item.status == 0);
			} else {
				list = this.studentList.filter((item) => item.machineId && stuList.includes(item.machineId - 0));
			}
			if (this.teacherInfo && this.teacherInfo.machineId && this.isVoiceDevice) {
				list.push({
					machineId: this.teacherInfo.machineId,
				});
			}
			if (list && list.length > 0) {
				if (this.isVoiceDevice) {
					let stulist = list.map((item) => {
						return {
							uid: item.machineId - 0,
							dev: 18,
						};
					});

					//46设备
					var message = {
						fun: 'wireless_list_bind_start',
						list: stulist,
					};
					this.WEBSOCKET_SEND(message);
					if (!this.stopDeviceEventList.includes('wireless_list_bind_stop')) {
						let eventlist = this.stopDeviceEventList || [];
						eventlist.push('wireless_list_bind_stop');
						this.SET_STOPDEVICEEVENTLIST(eventlist);
					}
				} else if (this.machineData.wareVersion != 'RP552G') {
					// if (!stuList) {
					// 	stuList = this.studentList.filter(item => item.machineId).map(item => item.machineId - 0);
					// }
					var message = {
						fun: 'wireless_bind_start',
						mode: 2, //自动绑定,4:刷卡绑定
						list: list.map((item) => item.machineId - 0),
					};
					this.WEBSOCKET_SEND(message);
					if (!this.stopDeviceEventList.includes('wireless_bind_stop')) {
						let eventlist = this.stopDeviceEventList || [];
						eventlist.push('wireless_bind_stop');
						this.SET_STOPDEVICEEVENTLIST(eventlist);
					}
				} else {
					list = list.map((item) => {
						return {
							uID: item.machineId - 0,
							name: ch2Unicdoe(item.studName),
							cla: ch2Unicdoe(item.className),
							team: beginClassData.alias
								? ch2Unicdoe(beginClassData.alias)
								: ch2Unicdoe(this.machineData.machId),
						};
					});
					var message = {
						fun: 'sync_ans_uidlist',
						type: 1,
						list: list,
					};
					this.WEBSOCKET_SEND(message);
				}
			}
		},

		//停止绑定学生
		stopBindStudent() {
			if (this.stopDeviceEventList.includes('wireless_bind_stop')) {
				this.WEBSOCKET_SEND({
					fun: 'wireless_bind_stop',
				});
				let stopDeviceEventList = [...this.stopDeviceEventList];
				stopDeviceEventList = stopDeviceEventList.filter((item) => item != 'wireless_bind_stop');
				this.SET_STOPDEVICEEVENTLIST(stopDeviceEventList);
			}
		},
		//显姓名班级
		updateName(uID, name, cla) {
			console.log('name', name, cla);
			if (this.isVoiceDevice) {
				console.log('到了46回显姓名');
				//46 答题器
				var message = {
					fun: 'dtq_echo_set',
					uID,
					msg: '   ' + name,
				};
				this.WEBSOCKET_SEND(message);
			} else if (this.machineData.wareVersion == 'RP552G') {
				//使用同步学生指令后，不需要再次配置学生姓名
			} else {
				var message = {
					fun: 'name_start',
					uID,
					name: ch2Unicdoe(name),
					cla: ch2Unicdoe(cla),
				};
				this.WEBSOCKET_SEND(message);
				if (!this.stopDeviceEventList.includes('name_stop')) {
					let eventlist = this.stopDeviceEventList || [];
					eventlist.push('name_stop');
					this.SET_STOPDEVICEEVENTLIST(eventlist);
				}
			}
		},
		//停止答题
		stopAnswer(sdTestQuestId, classId) {
			//有线
			if (this.deviceType == 'wired') {
				let msg = {
					fun: 'answer_stop',
				};
				this.WEBSOCKET_SEND(msg);
			}
			return this.$postAction(this.$sysManageapi.answerUrl.stopAnswer, {
				classId,
				sdTestQuestId,
				isWire: this.deviceType == 'wired' ? 1 : 0,
			}).then((res) => {
				console.log('停止答题' + JSON.stringify(res));
			});
		},
		//下课
		async endClass() {
			//下课时结束答题
			let sdTestQuestId = localStorage.getItem('sdTestQuestId');
			let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			if (tempsdTestQuestId) {
				await this.stopAnswer(tempsdTestQuestId, beginClassData.classId);
			} else {
				if (sdTestQuestId) {
					await this.stopAnswer(sdTestQuestId, beginClassData.classId);
				}
			}
			let parameter = {
				csId: beginClassData ? beginClassData.csId : '',
				isWire: this.deviceType == 'wired' ? 1 : 0,
			};
			this.spinning = true;
			startTime = new Date().getTime();
			//如果没有csId，也允许用户下课，不走下课接口
			if (!beginClassData || !beginClassData.csId) {
				this.endClassSuccess(startTime);
			}
			return this.$postAction(this.$sysManageapi.courseUrl.endClass, parameter).finally(() => {
				this.endClassSuccess(startTime);
			});
		},
		//下课成功操作
		endClassSuccess(startTime) {
			let len = this.stopDeviceEventList.length || 0;
			if (this.deviceType == 'wired') {
				//停止绑定学生，并清空白名单
				//反之停止指令没有下发成功，就发了其他指令，做延迟处理
				if (this.stopDeviceEventList && this.stopDeviceEventList.length > 0) {
					for (let i = 0; i < len; i++) {
						setTimeout(() => {
							this.WEBSOCKET_SEND({
								fun: this.stopDeviceEventList[i],
							});
						}, 50 * i);
					}
				}
			}
			setTimeout(() => {
				if (this.deviceType == 'wired') {
					if (this.machineData.machId) {
						this.clearWl(this.formData.classId);
						//552G,RP554需要清空白名单
						if (['RP554', 'RP552G'].includes(this.machineData.wareVersion)) {
							//清空设备白名单
							var message = {
								fun: 'clear_wl',
								uID: 0,
							};
							this.WEBSOCKET_SEND(message);
						}
					}
					//清空缓存答题数据
					this.$ls.remove('cardAnswerDate');
				}
				//清空数据缓存
				this.clearStorage();
			}, (len + 1) * 50);
			setTimeout(() => {
				//关闭链接
				if (this.websocketConncted) {
					this.WEBSOCKET_CLOSE();
				}
				//关闭小程序链接
				if (this.minProjectConncted) {
					this.MINPROJECT_CLOSE();
				}
				if (this.rabbitmqConncted && this.deviceType == 'wired') {
					this.destroyConnection();
				}
			}, (len + 2) * 50);
			setTimeout(() => {
				this.spinning = false;
				//清空学生名单
				this.SET_studentList([]);
				this.allstudentList = [];
				//清空设备信息
				this.machineData = {
					machId: '',
					online: 0,
					wareVersion: '',
					sdk_ver: '',
					version: '',
				};
				this.CLEAR_EVENTLIST();
				if (window.ipcRenderer) {
					window.ipcRenderer.send('onlinedirebro', 0);
				}
				//清空未处理的推送记录。
				this.$router.replace({
					path: '/user/login',
				});
			}, (len + 3) * 50 + 800);
		},
		//清空缓存
		clearStorage() {
			//this.$refs.componentstartAnswer&&this.$refs.componentstartAnswer.getDefaultFormData();
			this.SET_isAnswering(0);
			this.$ls.remove('beginClass'); //是否上课
			this.$ls.remove('importTopic'); //课件当前题
			this.$ls.remove('leftOperateData'); //左侧操作数据，主要用于是否刷卡绑定
			this.$ls.remove('isQuickanswer'); //清空抢答
			this.$ls.remove('feedbackId'); //清空反馈
			this.$ls.remove('signInInfo'); //清空签到信息
			this.$ls.remove('redpackId'); //清空抢红包
			this.REMOVE_tempTestData();
			this.$ls.remove('testData'); //答题测试
			this.curMenu = ''; //左侧操作页面组件
			this.$ls.remove('tempTopicData'); //临时题已发题号
			this.$ls.remove('testComponet'); //套题页面组件
			localStorage.removeItem('tempsdTestQuestId'); //临时题发题id
			localStorage.removeItem('sdTestQuestId'); //套题发题id
			localStorage.removeItem('tempsendTime'); //临时题发题时间
			localStorage.removeItem('answerTime'); //套题发题时间
			sessionStorage.setItem('isHasWxLoginTips', ''); //是否有小程序控制pc端提示
			this.SET_WHITELIST([]); //清空白名单
			this.SET_STOPDEVICEEVENTLIST([]);
			this.SET_sendTopicData({});
			this.SET_ANS_ID('');
		},
		/* 更新有线设备信息 */
		setWlList(device) {
			this.$postAction(this.$sysManageapi.uploadWiredUrl.setWlList, device);
		},
		/* 清空白名单 */
		clearWl(classId) {
			if (classId) {
				this.$postAction(this.$sysManageapi.uploadWiredUrl.clearWl + '?classId=' + classId);
			}
		},
		//重连SDK
		connctSDK() {
			this.showSdk = false;
			if (window.ipcRenderer) {
				window.ipcRenderer.send('connctSDK');
			} else {
				window.location.href = 'universalLink://';
			}
			setTimeout(() => {
				this.WEBSOCKET_RECONNECT('ws://127.0.0.1:8011');
			}, 500);
		},
		//重连SDK
		connctWebscoket() {
			this.WEBSOCKET_INIT('ws://127.0.0.1:8011', this.deviceType);
			this.showSdk = false;
		},
		//浏览器返回
		goBack() {
			let _this = this;
			let beginClass = this.$ls.get('beginClass');
			console.log('beginClass' + JSON.stringify(beginClass));
			if (!beginClass.isBegin) {
				return false;
			}
			let title = <div> 你确定要下课吗 ? </div>;
			this.$confirm({
				title: title,
				content: '下课后信息将不能恢复',
				okText: '确定',
				cancelText: '取消',
				class: 'confirmbox',
				okType: 'danger',
				onOk() {
					_this.endClass();
				},
				onCancel() {
					history.pushState(null, null, document.URL);
				},
			});
		},
		signInUpdate(signInUpdate) {
			//直接推送到队列
			this.sign_RABBITMQ_SEND(JSON.stringify(signInUpdate));
		},
		//查询老师信息
		getTeacherInfo() {
			this.$postAction(this.$sysManageapi.teacherUrl.getTeacherInfo).then((res) => {
				if (res && res.code == 1) {
					let teacherInfo = res.data;
					if (teacherInfo) {
						teacherInfo.status = 0;
						if (this.whiteList && this.whiteList.length > 0) {
							if (this.whiteList.includes(teacherInfo.machineId - 0)) {
								teacherInfo.status = '1';
							}
						}
					}
					this.SET_TEACHER_INFO(teacherInfo);
				}
			});
		},
	},
};
</script>

<style lang="less" scoped>
@import url('./base.less');

.left-bar {
	position: fixed;
	right: 0;
	/* position: absolute;
	left: 6px; */
	bottom: 200px;
	z-index: 999;
	width: 90px;

	/* &::before {
		content: '';
		position: absolute;
		top: 0;
		left: -6px;
		bottom: 0;
		width: 6px;
		height: 100%;
		background-color: @primary-color;
	} */

	.bar-side-inner {
		border: 2px solid @primary-color;
		/* border-radius: 0 10px 10px 0; */
		border-radius: 10px;
		position: relative;
		background: #fff;
		// border-left: 6px solid @primary-color;
		a {
			/* padding: 5px 20px; */
			margin: 5px 20px;
			&:first-child {
				padding-top: 10px;
			}

			&:last-child {
				padding-bottom: 10px;
			}

			text-align: center;

			.icon {
				width: 46px;
				height: 46px;
			}

			/* &:hover{
					background-color: rgba(0, 190, 197,0.1);
				} */
			&.selected {
			}
		}
	}
}
.myTree {
	width: 170px;
	height: 170px;
	position: absolute;
	bottom: 20px;
	left: 0;
	z-index: 9;
	.img {
		display: block;
		width: 100%;
		height: auto;
	}
}
.subjectName {
	position: absolute;
	left: 50%;
	top: 20%;
	transform: translate(-50%);
	z-index: 999;
	color: #fff;
	font-size: 40px;
}
/deep/ .ant-spin-container {
	height: 100%;
}
.countDownbox {
	position: absolute;
	top: 10px;
	right: 20px;
	font-size: 24px;
	z-index: 999;
	/deep/ .content {
		font-size: 24px;
	}
}
.popoverbox {
	width: 220px;
	text-align: center;
	a {
		margin: 10px;
		color: @primary-color;
	}
	.icon {
		width: 46px;
		height: 46px;
		margin: 0 auto;
	}
}
</style>
